package com.itdr.protal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itdr.common.Const;
import com.itdr.common.ServerResponse;
import com.itdr.pojo.Cart;
import com.itdr.pojo.Product;
import com.itdr.pojo.vo.CartProductVO;
import com.itdr.pojo.vo.CartToTalVO;
import com.itdr.protal.mapper.CartMapper;
import com.itdr.protal.mapper.ProductMapper;
import com.itdr.protal.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itdr.utils.VOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author AirZhang
 * @since 2020-10-20
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    @Resource
    CartMapper cartMapper;

    @Resource
    ProductMapper productMapper;

    private List<CartProductVO> getCartProductVO(List<Cart> cartList){
        List<CartProductVO> voList = new ArrayList<>();
        for (Cart cart : cartList) {
            Product product = productMapper.selectById(cart.getProductId());
            // 4.查询到的商品信息是否存在，并且是在售状态
            if (product != null && product.getStatus().equals(1)) {
                CartProductVO cartProductVO = VOUtil.getCartProductVO(cart, product);
                voList.add(cartProductVO);
            }
        }
        return voList;
    }

    private Page getCartPage(Page cartPage) {
        List<Cart> cartList = cartPage.getRecords();
        List<CartProductVO> voList = getCartProductVO(cartList);
        cartPage.setRecords(voList);
        return cartPage;
    }

    @Override
    public ServerResponse total(Integer id) {

        BigDecimal totalPrice = new BigDecimal("0");
        Integer num = 0;
        // 1.查找一下当前这个登录用户，购物车中选中的商品
        Map m = new HashMap();
        m.put("user_id",id);
        m.put("checked",1);
        List<Cart> cartList = cartMapper.selectList(new QueryWrapper<Cart>().allEq(m));
        if(cartList.size() == 0){
            CartToTalVO cartToTalVO = VOUtil.getCartToTalVO(totalPrice, num);
            return ServerResponse.toSuccess(cartToTalVO);
        }

        // 2.原始数据处理
        num = cartList.size();
        List<CartProductVO> voList = getCartProductVO(cartList);
        for (CartProductVO cartProductVO : voList) {
            BigDecimal multiply = cartProductVO.getPrice().multiply(new BigDecimal(String.valueOf(cartProductVO.getQuantity())));
            totalPrice = totalPrice.add(multiply);
        }
        // 2.计算一下选中商品的总价格
        CartToTalVO cartToTalVO = VOUtil.getCartToTalVO(totalPrice, num);
        return ServerResponse.toSuccess(cartToTalVO);

    }

    @Override
    public ServerResponse listAll(Integer uid, Integer pageNum, Integer pageSize) {
        List voList = new ArrayList<>();

        // 1.查询当前用户购物车信息
        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().eq("user_id", uid));
        List<Cart> cartList = cartPage.getRecords();
        // 2.购物车为空
        if (cartList.size() == 0) {
            return ServerResponse.toFail(Const.CartEnum.EMPTY_CART.getCode(), Const.CartEnum.EMPTY_CART.getDesc());
        }
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }

    @Override
    public ServerResponse add(Integer uid, Integer pid, Integer num, Integer pageNum, Integer pageSize) {
        // 1.判断商品是否存在，并且在售
        Product product = productMapper.selectById(pid);
        if (product == null) {
            return ServerResponse.toFail(Const.ProductEnum.NO_PRODUCT.getCode(), Const.ProductEnum.NO_PRODUCT.getDesc());
        }
        if (!product.getStatus().equals(1)) {
            return ServerResponse.toFail(Const.ProductEnum.OUT_PRODUCT.getCode(), Const.ProductEnum.OUT_PRODUCT.getDesc());
        }

        // 2.判断商品是否已经存在与购物车中
        Map m = new HashMap();
        m.put("product_id", pid);
        m.put("user_id", uid);
        Cart cart = cartMapper.selectOne(new QueryWrapper<>().allEq(m));
        //存在就在原有数量上增加
        if (cart != null) {
            //判断商品购买数量，是否超出商品库存
            //不超出不做任何处理
            //超出就把购物数量设定为商品库存最大值
            Integer a = cart.getQuantity() + num;
            if (a > product.getStock()) {
                a = product.getStock();
            }
            int update = cartMapper.update(null, new UpdateWrapper<Cart>().set("quantity", a).allEq(m));
            if (update <= 0) {
                return ServerResponse.toFail(Const.CartEnum.UPDATE_CART.getCode(), Const.CartEnum.UPDATE_CART.getDesc());
            }
        } else {
            //不存在就新增一条购物车信息
            Cart c = new Cart();
            c.setUserId(uid);
            c.setProductId(pid);
            if (num > product.getStock()) {
                num = product.getStock();
            }
            c.setQuantity(num);
            c.setChecked(1);
            c.setCreateTime(new Date());
            c.setUpdateTime(new Date());
            int insert = cartMapper.insert(c);
            if (insert <= 0) {
                return ServerResponse.toFail(Const.CartEnum.UPDATE_CART.getCode(), Const.CartEnum.UPDATE_CART.getDesc());
            }
        }

        // 返回成功数据
        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().eq("user_id", uid));
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }

    @Override
    public ServerResponse updateOne(Integer uid, Integer pid, Integer num, Integer pageNum, Integer pageSize) {
        Product product = productMapper.selectById(pid);
        if (product == null) {
            return ServerResponse.toFail(Const.ProductEnum.NO_PRODUCT.getCode(), Const.ProductEnum.NO_PRODUCT.getDesc());
        }
        if (!product.getStatus().equals(1)) {
            return ServerResponse.toFail(Const.ProductEnum.OUT_PRODUCT.getCode(), Const.ProductEnum.OUT_PRODUCT.getDesc());
        }

        // 2.判断商品是否已经存在与购物车中
        Map m = new HashMap();
        m.put("product_id", pid);
        m.put("user_id", uid);

        //判断商品购买数量，是否超出商品库存
        //不超出不做任何处理
        //超出就把购物数量设定为商品库存最大值
        if (num > product.getStock()) {
            num = product.getStock();
        }
        int update = cartMapper.update(null, new UpdateWrapper<Cart>().set("quantity", num).allEq(m));
        if (update <= 0) {
            return ServerResponse.toFail(Const.CartEnum.UPDATE_CART.getCode(), Const.CartEnum.UPDATE_CART.getDesc());
        }

        // 返回成功数据
        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().eq("user_id", uid));
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }

    @Override
    public ServerResponse deleteOne(Integer uid, Integer pid, Integer pageNum, Integer pageSize) {
        Map m = new HashMap();
        m.put("product_id", pid);
        m.put("user_id", uid);
        int delete = cartMapper.delete(new UpdateWrapper<Cart>().allEq(m));
        if (delete <= 0) {
            return ServerResponse.toFail(Const.CartEnum.DELETE_CART.getCode(), Const.CartEnum.DELETE_CART.getDesc());
        }

        // 返回成功数据
        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().eq("user_id", uid));
        List<Cart> cartList = cartPage.getRecords();
        // 购物车为空
        if (cartList.size() == 0) {
            return ServerResponse.toFail(Const.CartEnum.EMPTY_CART.getCode(), Const.CartEnum.EMPTY_CART.getDesc());
        }
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }

    @Override
    public ServerResponse deleteAll(Integer uid) {
        int delete = cartMapper.delete(new UpdateWrapper<Cart>().eq("user_id", uid));
        if (delete <= 0) {
            return ServerResponse.toFail(Const.CartEnum.DELETE_CART.getCode(), Const.CartEnum.DELETE_CART.getDesc());
        }
        return ServerResponse.toSuccess(Const.CartEnum.EMPTY_CART.getDesc());
    }

    @Override
    public ServerResponse checked(Integer uid, Integer pid, Integer pageNum, Integer pageSize) {
        // 1.判断购物车信息是否存在
        Map m = new HashMap();
        m.put("product_id", pid);
        m.put("user_id", uid);
        Cart cart = cartMapper.selectOne(new QueryWrapper<>().allEq(m));
        if (cart == null) {
            return ServerResponse.toFail(Const.CartEnum.NO_UPDATE_CART.getCode(), Const.CartEnum.NO_UPDATE_CART.getDesc());
        }

        // 2.判断商品是否存在，并且在售
        Product product = productMapper.selectById(pid);
        if (product == null) {
            return ServerResponse.toFail(Const.ProductEnum.NO_PRODUCT.getCode(), Const.ProductEnum.NO_PRODUCT.getDesc());
        }
        if (!product.getStatus().equals(1)) {
            return ServerResponse.toFail(Const.ProductEnum.OUT_PRODUCT.getCode(), Const.ProductEnum.OUT_PRODUCT.getDesc());
        }

        // 3.修改购物信息选中状态
        Integer n = 1;
        if (cart.getChecked().equals(1)) {
            n = 0;
        }
        int update = cartMapper.update(null, new UpdateWrapper<Cart>().set("checked", n).allEq(m));
        if (update <= 0) {
            return ServerResponse.toFail(Const.CartEnum.UPDATE_CART.getCode(),Const.CartEnum.UPDATE_CART.getDesc());
        }

        // 返回成功数据
        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().eq("user_id", uid));
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }

    @Override
    public ServerResponse checkedAll(Integer uid, Integer pageNum, Integer pageSize) {
        // 1.购物车是否为空
        List<Cart> cartList = cartMapper.selectList(new QueryWrapper<Cart>().eq("user_id", uid));
        if (cartList.size() == 0) {
            return ServerResponse.toFail(Const.CartEnum.EMPTY_CART.getCode(), Const.CartEnum.EMPTY_CART.getDesc());
        }

        // 2.全选或非全选
        Integer n = 0;
        for (Cart cart : cartList) {
            if(cart.getChecked().equals(0)){
                n = 1;
            }
        }

        int update = cartMapper.update(null, new UpdateWrapper<Cart>().set("checked", n).eq("user_id", uid));
        if (update <= 0) {
            return ServerResponse.toFail(Const.CartEnum.UPDATE_CART.getCode(),Const.CartEnum.UPDATE_CART.getDesc());
        }


        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().eq("user_id", uid));
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }

    @Override
    public ServerResponse selectChecked(Integer uid, Integer pageNum, Integer pageSize) {
        Map m = new HashMap();
        m.put("checked", 1);
        m.put("user_id", uid);
        Page<Cart> cartPage = cartMapper.selectPage(new Page<Cart>(pageNum, pageSize), new QueryWrapper<Cart>().allEq(m));
        cartPage = getCartPage(cartPage);
        return ServerResponse.toSuccess(cartPage);
    }
}
